<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"vchao.top","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="前言世界上没有完美的代码，你永远不知道bug什么时候会来……  &#x2F;** 不要犹豫了，赶紧给你的代码上份保险吧，不要三四千，不要一两千，只要花10分钟复制下代码就好啦！*&#x2F; 算了，这段话假装没有看见吧……  分析对于所有的客户端程序来说，环境的复杂性和不可控性总会导致各种各样意料之外的bug。这点对是国内的安卓开发者来说尤为明显。首先安卓就有多个版本，从2.X到9.X，其次国内厂商的多种定制ROM更">
<meta property="og:type" content="article">
<meta property="og:title" content="给APP上份保险：安卓的全局异常捕获">
<meta property="og:url" content="http://vchao.top/2021/08/25/%E7%BB%99APP%E4%B8%8A%E4%BB%BD%E4%BF%9D%E9%99%A9%EF%BC%9A%E5%AE%89%E5%8D%93%E7%9A%84%E5%85%A8%E5%B1%80%E5%BC%82%E5%B8%B8%E6%8D%95%E8%8E%B7/index.html">
<meta property="og:site_name" content="乘风破浪">
<meta property="og:description" content="前言世界上没有完美的代码，你永远不知道bug什么时候会来……  &#x2F;** 不要犹豫了，赶紧给你的代码上份保险吧，不要三四千，不要一两千，只要花10分钟复制下代码就好啦！*&#x2F; 算了，这段话假装没有看见吧……  分析对于所有的客户端程序来说，环境的复杂性和不可控性总会导致各种各样意料之外的bug。这点对是国内的安卓开发者来说尤为明显。首先安卓就有多个版本，从2.X到9.X，其次国内厂商的多种定制ROM更">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-08-25T14:42:51.249Z">
<meta property="article:modified_time" content="2021-08-25T14:37:20.814Z">
<meta property="article:author" content="vchao">
<meta property="article:tag" content="Android">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://vchao.top/2021/08/25/%E7%BB%99APP%E4%B8%8A%E4%BB%BD%E4%BF%9D%E9%99%A9%EF%BC%9A%E5%AE%89%E5%8D%93%E7%9A%84%E5%85%A8%E5%B1%80%E5%BC%82%E5%B8%B8%E6%8D%95%E8%8E%B7/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>给APP上份保险：安卓的全局异常捕获 | 乘风破浪</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">乘风破浪</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://vchao.top/2021/08/25/%E7%BB%99APP%E4%B8%8A%E4%BB%BD%E4%BF%9D%E9%99%A9%EF%BC%9A%E5%AE%89%E5%8D%93%E7%9A%84%E5%85%A8%E5%B1%80%E5%BC%82%E5%B8%B8%E6%8D%95%E8%8E%B7/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="vchao">
      <meta itemprop="description" content="怀揣好奇，梦想改变世界的菜鸟极客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="乘风破浪">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          给APP上份保险：安卓的全局异常捕获
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-08-25 22:42:51 / 修改时间：22:37:20" itemprop="dateCreated datePublished" datetime="2021-08-25T22:42:51+08:00">2021-08-25</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index"><span itemprop="name">Android</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>世界上没有完美的代码，你永远不知道bug什么时候会来……</p>
<blockquote>
<p>/** 不要犹豫了，赶紧给你的代码上份保险吧，不要三四千，不要一两千，只要花10分钟复制下代码就好啦！*/ 算了，这段话假装没有看见吧……</p>
</blockquote>
<h1 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h1><p>对于所有的客户端程序来说，环境的复杂性和不可控性总会导致各种各样意料之外的bug。这点对是国内的安卓开发者来说尤为明显。<br>首先安卓就有多个版本，从2.X到9.X，其次国内厂商的多种定制ROM更加剧了这个复杂程度……<br>总而言之，稳定性测试是保障客户端稳定性的一种手段，收集更多异常信息，复现问题解决问题。</p>
<p>那么当Android客户端发生闪退时，是如何捕获到闪退信息的呢？</p>
<h2 id="Java的异常"><a href="#Java的异常" class="headerlink" title="Java的异常"></a>Java的异常</h2><p>Java语言在设计之初就提供了相对完美的异常处理机制，所有的异常类是从java.lang,Exception类继承的子类，Exception类是Throwable类的子类，除了Exception,Throwable还有一个子类Error，在java中只有Throwable类型的实例才可以被抛出（throw）或者（catch）,它是异常处理机制的基本组成部分。</p>
<p><strong>Exception和Error</strong><br>Exception和Error体现了Java平台设计者对不同异常情况的分类，Exception是程序正常运行中，可以预料的意外情况，可能并且应该被捕获。Error是指在正常情况下，不太可能出现的情况，绝大部分的Error都会导致程序处理非正常的，不可恢复的状态，例如典型的OutOfMemoryError.</p>
<blockquote>
<p>Exception分为可检查异常（checked）和不检查异常（unchecked）异常，可检查异常必须在代码里显式进行捕获处理，这是编译期检查的一部分。不检查异常是所谓的运行时异常，类似NullPointException,ArrayIndexOutOfBoundsException,不会在编译器进行检查。</p>
</blockquote>
<h2 id="扩展知识"><a href="#扩展知识" class="headerlink" title="扩展知识"></a>扩展知识</h2><p>关于异常捕获的基本原则：<br>1.尽量不要捕获类似Exception这样的异常，应该捕获特定的异常。<br>2.不要生吞异常（swallow），因为这样可能会导致非常难以诊断的诡异情况。<br>3.try-catch代码段会产生额外的性能开销，换个角度，它往往会影响JVM对代码进行优化，所以建议仅仅捕获有必要的代码，尽量不要一个大的try包住整段的代码。<br>4.Java每实例化一个Exception，都会对当时的栈进行快照，这是一个非常重的操作，如果很频繁，这个开销就不能被忽略了。</p>
<h2 id="RuntimeException的异常导致的app崩溃，应该如何来捕获？"><a href="#RuntimeException的异常导致的app崩溃，应该如何来捕获？" class="headerlink" title="RuntimeException的异常导致的app崩溃，应该如何来捕获？"></a>RuntimeException的异常导致的app崩溃，应该如何来捕获？</h2><p>Android全局异常捕获Android应用不可避免的发生crash,也就是崩溃，不同厂商的Rom,硬件导致的兼容性问题，都会导致应该异常或者崩溃。<br>接下来看一下Thread类里面的UncaugthExceptionHandler静态接口，ThreadGroup是它的子类，抽象方法uncaughtException(Thread t,Throwable e)。<br>官方文档是这样介绍的，<br>Thread.UncauthExceptionHandler接口，uncaught exception发生，一个线程突然停止，它的处理者（handler）,就会被调用。<br>JVM会通过Thread.getUncauthException()查询线程的UncaughtExceptionHandler,同时唤起处理者的uncaughtException方法，thread和exception作为参数传递，</p>
<p>如果一个线程没有UncaughtExceptionHandker，这时ThreadGroup对象作为该线程的UncaughtExceptionHandler,ThreadGroup没有明确的需求处理异常，它可以把调用传递给default uncauth exception handler.下面通过一个demo演示全局异常捕获</p>
<p>Thread.UncaughtExceptionHandler是一个当线程由于未捕获的异常突然终止而调用处理程序的接口.<br>当线程由于未捕获的异常即将终止时，Java虚拟机将使用它来查询其UncaughtExceptionHandler的线程Thread.getUncaughtExceptionHandler()，并将调用处理程序的 uncaughtException方法，将线程和异常作为参数传递。如果一个线程没有显示它的UncaughtExceptionHandler，那么它的ThreadGroup对象充当它的 UncaughtExceptionHandler。如果ThreadGroup对象没有处理异常的特殊要求，它可以将调用转发到默认的未捕获的异常处理程序。</p>
<h2 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h2><p>因此我们可以自定一个类去实现该接口，该类主要用于收集错误信息和保存错误信息.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 作用:</span></span><br><span class="line"><span class="comment"> * 1.收集错误信息</span></span><br><span class="line"><span class="comment"> * 2.保存错误信息</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CrashHandler</span> <span class="keyword">implements</span> <span class="title">Thread</span>.<span class="title">UncaughtExceptionHandler</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> CrashHandler sInstance = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">private</span> Thread.UncaughtExceptionHandler mDefaultHandler;</span><br><span class="line">    <span class="keyword">private</span> Context mContext;</span><br><span class="line">    <span class="comment">// 保存手机信息和异常信息</span></span><br><span class="line">    <span class="keyword">private</span> Map&lt;String, String&gt; mMessage = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> CrashHandler <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (sInstance == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (CrashHandler.class) &#123;</span><br><span class="line">                <span class="keyword">if</span> (sInstance == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="keyword">synchronized</span> (CrashHandler.class) &#123;</span><br><span class="line">                        sInstance = <span class="keyword">new</span> CrashHandler();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sInstance;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">CrashHandler</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 初始化默认异常捕获</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> context context</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">(Context context)</span> </span>&#123;</span><br><span class="line">        mContext = context;</span><br><span class="line">        <span class="comment">// 获取默认异常处理器</span></span><br><span class="line">        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();</span><br><span class="line">        <span class="comment">// 将此类设为默认异常处理器</span></span><br><span class="line">        Thread.setDefaultUncaughtExceptionHandler(<span class="keyword">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">uncaughtException</span><span class="params">(Thread t, Throwable e)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!handleException(e)) &#123;</span><br><span class="line">            <span class="comment">// 未经过人为处理,则调用系统默认处理异常,弹出系统强制关闭的对话框</span></span><br><span class="line">            <span class="keyword">if</span> (mDefaultHandler != <span class="keyword">null</span>) &#123;</span><br><span class="line">                mDefaultHandler.uncaughtException(t, e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 已经人为处理,系统自己退出</span></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e1) &#123;</span><br><span class="line">                e1.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            Process.killProcess(Process.myPid());</span><br><span class="line">            System.exit(<span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 是否人为捕获异常</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> e Throwable</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> true:已处理 false:未处理</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">handleException</span><span class="params">(Throwable e)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (e == <span class="keyword">null</span>) &#123;<span class="comment">// 异常是否为空</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">new</span> Thread() &#123;<span class="comment">// 在主线程中弹出提示</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                Looper.prepare();</span><br><span class="line">                Toast.makeText(mContext, <span class="string">&quot;捕获到异常&quot;</span>, Toast.LENGTH_SHORT).show();</span><br><span class="line">                Looper.loop();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;.start();</span><br><span class="line">        collectErrorMessages();</span><br><span class="line">        saveErrorMessages(e);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 1.收集错误信息</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">collectErrorMessages</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        PackageManager pm = mContext.getPackageManager();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);</span><br><span class="line">            <span class="keyword">if</span> (pi != <span class="keyword">null</span>) &#123;</span><br><span class="line">                String versionName = TextUtils.isEmpty(pi.versionName) ? <span class="string">&quot;null&quot;</span> : pi.versionName;</span><br><span class="line">                String versionCode = <span class="string">&quot;&quot;</span> + pi.versionCode;</span><br><span class="line">                mMessage.put(<span class="string">&quot;versionName&quot;</span>, versionName);</span><br><span class="line">                mMessage.put(<span class="string">&quot;versionCode&quot;</span>, versionCode);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 通过反射拿到错误信息</span></span><br><span class="line">            Field[] fields = Build.class.getFields();</span><br><span class="line">            <span class="keyword">if</span> (fields != <span class="keyword">null</span> &amp;&amp; fields.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">for</span> (Field field : fields) &#123;</span><br><span class="line">                    field.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        mMessage.put(field.getName(), field.get(<span class="keyword">null</span>).toString());</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (IllegalAccessException e) &#123;</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (PackageManager.NameNotFoundException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 2.保存错误信息</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> e Throwable</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">saveErrorMessages</span><span class="params">(Throwable e)</span> </span>&#123;</span><br><span class="line">        StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">        <span class="keyword">for</span> (Map.Entry&lt;String, String&gt; entry : mMessage.entrySet()) &#123;</span><br><span class="line">            String key = entry.getKey();</span><br><span class="line">            String value = entry.getValue();</span><br><span class="line">            sb.append(key).append(<span class="string">&quot;=&quot;</span>).append(value).append(<span class="string">&quot;\n&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        Writer writer = <span class="keyword">new</span> StringWriter();</span><br><span class="line">        PrintWriter pw = <span class="keyword">new</span> PrintWriter(writer);</span><br><span class="line">        e.printStackTrace(pw);</span><br><span class="line">        Throwable cause = e.getCause();</span><br><span class="line">        <span class="comment">// 循环取出Cause</span></span><br><span class="line">        <span class="keyword">while</span> (cause != <span class="keyword">null</span>) &#123;</span><br><span class="line">            cause.printStackTrace(pw);</span><br><span class="line">            cause = e.getCause();</span><br><span class="line">        &#125;</span><br><span class="line">        pw.close();</span><br><span class="line">        String result = writer.toString();</span><br><span class="line">        sb.append(result);</span><br><span class="line">        String time = <span class="keyword">new</span> SimpleDateFormat(<span class="string">&quot;yyyy-MM-dd HH:mm:ss&quot;</span>, Locale.CHINA).format(<span class="keyword">new</span> Date());</span><br><span class="line">        String fileName = <span class="string">&quot;crash-&quot;</span> + time + <span class="string">&quot;-&quot;</span> + System.currentTimeMillis() + <span class="string">&quot;.log&quot;</span>;</span><br><span class="line">        <span class="comment">// 有无SD卡</span></span><br><span class="line">        <span class="keyword">if</span> (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) &#123;</span><br><span class="line">            String path = Environment.getExternalStorageDirectory().getPath() + <span class="string">&quot;crash/&quot;</span>;</span><br><span class="line">            File dir = <span class="keyword">new</span> File(path);</span><br><span class="line">            <span class="keyword">if</span> (!dir.exists()) dir.mkdirs();</span><br><span class="line">            FileOutputStream fos = <span class="keyword">null</span>;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                fos = <span class="keyword">new</span> FileOutputStream(path + fileName);</span><br><span class="line">                fos.write(sb.toString().getBytes());</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e1) &#123;</span><br><span class="line">                e1.printStackTrace();</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> (fos != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        fos.close();</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (IOException e1) &#123;</span><br><span class="line">                        e1.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><p>在Application中调用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CrashHandler.getInstance().init(<span class="keyword">this</span>);</span><br></pre></td></tr></table></figure>
<p>逻辑代码中，随便new RuntimeException(“XXX 自定义异常”)，或者写一个固定这时uncaughtHandlerException就可以捕获程序的异常了。</p>
<p>本文参考：<br><a target="_blank" rel="noopener" href="https://blog.csdn.net/klxh2009/article/details/77480108">https://blog.csdn.net/klxh2009/article/details/77480108</a><br><a target="_blank" rel="noopener" href="https://www.cnblogs.com/sesexxoo/p/6190507.html">https://www.cnblogs.com/sesexxoo/p/6190507.html</a><br><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/84eba8efa45e">https://www.jianshu.com/p/84eba8efa45e</a></p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Android/" rel="tag"># Android</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/08/25/%E7%BA%B3%E5%B0%BC%EF%BC%9FCollections%E5%AF%B9%E6%97%B6%E9%97%B4%E6%88%B3%E6%8E%92%E5%BA%8F%E5%87%BA%E9%94%99%E4%BA%86%EF%BC%9F%EF%BC%9F/" rel="prev" title="纳尼？Collections对时间戳排序出错了？？">
      <i class="fa fa-chevron-left"></i> 纳尼？Collections对时间戳排序出错了？？
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/08/25/%E8%AE%B0%E4%B8%80%E6%AC%A1%E9%80%82%E9%85%8Dbug%E8%A7%A3%E5%86%B3%E8%BF%87%E7%A8%8B%EF%BC%8C%E6%9D%83%E7%94%A8%E4%BD%9C%E7%BB%8F%E9%AA%8C%E6%95%99%E8%AE%AD%E5%88%86%E4%BA%AB/" rel="next" title="记一次适配bug解决过程，权用作经验教训分享">
      记一次适配bug解决过程，权用作经验教训分享 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%89%8D%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%88%86%E6%9E%90"><span class="nav-number">2.</span> <span class="nav-text">分析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Java%E7%9A%84%E5%BC%82%E5%B8%B8"><span class="nav-number">2.1.</span> <span class="nav-text">Java的异常</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%89%A9%E5%B1%95%E7%9F%A5%E8%AF%86"><span class="nav-number">2.2.</span> <span class="nav-text">扩展知识</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#RuntimeException%E7%9A%84%E5%BC%82%E5%B8%B8%E5%AF%BC%E8%87%B4%E7%9A%84app%E5%B4%A9%E6%BA%83%EF%BC%8C%E5%BA%94%E8%AF%A5%E5%A6%82%E4%BD%95%E6%9D%A5%E6%8D%95%E8%8E%B7%EF%BC%9F"><span class="nav-number">2.3.</span> <span class="nav-text">RuntimeException的异常导致的app崩溃，应该如何来捕获？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0"><span class="nav-number">2.4.</span> <span class="nav-text">实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8"><span class="nav-number">2.5.</span> <span class="nav-text">使用</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">vchao</p>
  <div class="site-description" itemprop="description">怀揣好奇，梦想改变世界的菜鸟极客</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">46</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">分类</span>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">冀ICP备 17022751号-1 </a>
      <img src="https://beian.miit.gov.cn" style="display: inline-block;">
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vchao</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
